package com.xwh.shop.orders.service.handlers;

import com.xwh.shop.common.Result;
import com.xwh.shop.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {


    // 看到业务异常 说明是BusinessException

    @ExceptionHandler(BusinessException.class)
    public Result<Object> handleException(BusinessException e) {
        log.error("业务异常：{}", e.getResp().getMessage());
        return Result.error(200, e.getResp().getCode(), e.getResp().getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));

        log.error("参数校验失败: {}", errorMessage);
        return Result.error(-1, -1, errorMessage);
    }

    // 看到系统繁忙 说明是RuntimeException

    @ExceptionHandler(RuntimeException.class)
    public Result<Object> handleException(RuntimeException e) {
        log.error("系统运行时异常：", e);
        return Result.error(-1, -1, "系统繁忙，请稍后再试");
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        log.error("系统未处理异常：", e);
        return Result.error(-1, -1, "系统异常，请联系管理员");
    }
}
